<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/11
 * Time: 9:35
 */

namespace app\api\validate;


use app\lib\exception\BannerMissException;
use app\lib\exception\ParameterException;
use think\Exception;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    public function goCheck()
    {
        //获取http传入的参数
        $request = Request::instance();
        $params = $request->param();
        //对参数进行校验
        $result = $this->batch()->check($params);
        if (!$result){
            $e = new ParameterException(['msg'=>$this->error]);
            throw $e;

        }else{
            return true;
        }
    }

    //定义id验证规则 是否是整数
    protected function isPositiveIntger($value, $rule='', $data='',$field=''){
        if (is_numeric($value) &&is_int($value + 0) && ($value +0) > 0)
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    /*不为空*/
    protected function isNotEmpty($value,$rule='',$date='',$field=''){
        if (empty($value)){
            return false;
        }else{
            return true;
        }
    }

    /*过滤多余的字段*/
    public function getDataByRule($arrays)
    {
        if (array_key_exists('user_id',$arrays) | array_key_exists('uid',$arrays)){
            //不允许包含user_id和uid 防止而已覆盖user_id外键
            throw new ParameterException(['msg'=>'参数包含非法参数名']);
        }

        /*保存变量具体取值*/
        $newArray = [];
        foreach ($this->rule as $key=>$value){
            $newArray[$key] = $arrays[$key];
        }
        return $newArray;
    }

    //没有使用TP的正则验证，集中在一处方便以后修改
    //不推荐使用正则，因为复用性太差
    //手机号的验证规则
    protected function isMobile($value)
    {
        $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
}